<?php

namespace Kunfeng\Dify\Validator;

use Kunfeng\Dify\Exception\ValidationException;
use Kunfeng\Dify\Model\DifyConfig;

/**
 * 配置验证器
 */
class ConfigValidator
{
    /**
     * 验证配置
     */
    public static function validate(DifyConfig $config): void
    {
        self::validateBaseUrl($config->getBaseUrl());
        self::validateApiKey($config->getApiKey());
        self::validateTimeouts($config);
    }

    /**
     * 验证基础URL
     */
    private static function validateBaseUrl(string $baseUrl): void
    {
        if (empty($baseUrl)) {
            throw ValidationException::requiredField('baseUrl');
        }

        if (!filter_var($baseUrl, FILTER_VALIDATE_URL)) {
            throw ValidationException::forField('baseUrl', $baseUrl, 'Invalid URL format');
        }

        // 确保URL以http或https开头
        if (!preg_match('/^https?:\/\//', $baseUrl)) {
            throw ValidationException::forField('baseUrl', $baseUrl, 'URL must start with http:// or https://');
        }
    }

    /**
     * 验证API密钥
     */
    private static function validateApiKey(string $apiKey): void
    {
        if (empty($apiKey)) {
            throw ValidationException::requiredField('apiKey');
        }

        if (strlen($apiKey) < 10) {
            throw ValidationException::forField('apiKey', $apiKey, 'API key is too short');
        }
    }

    /**
     * 验证超时配置
     */
    private static function validateTimeouts(DifyConfig $config): void
    {
        $connectTimeout = $config->getConnectTimeout();
        $readTimeout = $config->getReadTimeout();
        $writeTimeout = $config->getWriteTimeout();

        if ($connectTimeout < 1000) {
            throw ValidationException::forField('connectTimeout', $connectTimeout, 'Connect timeout must be at least 1000ms');
        }

        if ($readTimeout < 1000) {
            throw ValidationException::forField('readTimeout', $readTimeout, 'Read timeout must be at least 1000ms');
        }

        if ($writeTimeout < 1000) {
            throw ValidationException::forField('writeTimeout', $writeTimeout, 'Write timeout must be at least 1000ms');
        }

        if ($readTimeout < $connectTimeout) {
            throw ValidationException::forField('readTimeout', $readTimeout, 'Read timeout must be greater than or equal to connect timeout');
        }
    }

    /**
     * 验证HTTP选项
     */
    public static function validateHttpOptions(array $httpOptions): void
    {
        if (isset($httpOptions['timeout']) && $httpOptions['timeout'] < 1) {
            throw ValidationException::forField('httpOptions.timeout', $httpOptions['timeout'], 'Timeout must be at least 1 second');
        }

        if (isset($httpOptions['connect_timeout']) && $httpOptions['connect_timeout'] < 1) {
            throw ValidationException::forField('httpOptions.connect_timeout', $httpOptions['connect_timeout'], 'Connect timeout must be at least 1 second');
        }
    }
}
